package fenyu.personblob.web.util;

import com.google.gson.Gson;
import fenyu.personblob.bean.databean.User;
import fenyu.personblob.bean.strategy.Strategy;
import fenyu.personblob.single.SinglePathDoor;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import static javax.crypto.Cipher.getInstance;

/**
 * create at 2018/12/22 10:52
 *
 * @author 纷羽 <gzj0078@gmail.com>
 */
public class TokenGetUserStrategy implements Strategy {

    @Override
    public Object todo(Object... args) {
        String token = (String) args[0];
        try {
            String data = rsaDecode(token);
            TokenSave dobject = new Gson().fromJson(data, TokenSave.class);
            Integer user_id = dobject.getId();
            String key = dobject.getKey();
            User user = SinglePathDoor.getSingleSave().getSaveDoor().getUserSavePath().getById(user_id);
            if (user != null && user.getToken().equals(key))
                return user;
            else
                return null;
        } catch (Exception e) {
            return null;
        }
    }

    private String rsaDecode(String code) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] datas = Base64.decodeBase64(code);
        PrivateKey privateKey = SinglePathDoor.getSingleSave().getSaveDoor().getKEY_PAIR().getPrivate();
        Cipher cipher = getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bt_original = cipher.doFinal(datas);
        return new String(bt_original);
    }
}
